package com.it.smartoldb.service;

import com.it.smartoldb.entity.HealthRecord;
import com.it.smartoldb.repository.HealthRecordRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * 健康记录服务类
 */
@Service
@Transactional
public class HealthRecordService {

    @Autowired
    private HealthRecordRepository healthRecordRepository;

    /**
     * 创建健康记录
     */
    public HealthRecord createHealthRecord(HealthRecord healthRecord) {
        if (healthRecord.getRecordTime() == null) {
            healthRecord.setRecordTime(LocalDateTime.now());
        }
        
        // 自动判断状态
        if (healthRecord.getStatus() == null || healthRecord.getStatus().isEmpty()) {
            healthRecord.setStatus(determineHealthStatus(healthRecord));
        }
        
        return healthRecordRepository.save(healthRecord);
    }

    /**
     * 判断健康状态
     */
    private String determineHealthStatus(HealthRecord record) {
        String recordType = record.getRecordType();
        
        try {
            switch (recordType) {
                case "blood_pressure":
                    return determineBloodPressureStatus(record);
                case "blood_sugar":
                    return determineBloodSugarStatus(record);
                case "temperature":
                    return determineTemperatureStatus(record);
                case "heart_rate":
                    return determineHeartRateStatus(record);
                case "weight":
                    return "normal"; // 体重需要更复杂的判断，暂时返回正常
                default:
                    return "normal";
            }
        } catch (Exception e) {
            return "normal";
        }
    }
    
    private String determineBloodPressureStatus(HealthRecord record) {
        Integer systolic = record.getSystolicPressure();
        Integer diastolic = record.getDiastolicPressure();
        
        if (systolic == null || diastolic == null) {
            return "normal";
        }
        
        // 高血压判断标准
        if (systolic >= 140 || diastolic >= 90) {
            return "high";
        }
        // 低血压判断标准
        if (systolic < 90 || diastolic < 60) {
            return "low";
        }
        
        return "normal";
    }
    
    private String determineBloodSugarStatus(HealthRecord record) {
        BigDecimal value = record.getValue();
        if (value == null) return "normal";
        
        double bloodSugar = value.doubleValue();
        
        // 高血糖判断标准 (随机血糖 > 11.1 mmol/L)
        if (bloodSugar > 11.1) {
            return "high";
        }
        // 低血糖判断标准 (< 3.9 mmol/L)
        if (bloodSugar < 3.9) {
            return "low";
        }
        
        return "normal";
    }
    
    private String determineTemperatureStatus(HealthRecord record) {
        BigDecimal value = record.getValue();
        if (value == null) return "normal";
        
        double temperature = value.doubleValue();
        
        // 发热判断标准 (> 37.5°C)
        if (temperature > 37.5) {
            return "high";
        }
        // 体温过低判断标准 (< 36.0°C)
        if (temperature < 36.0) {
            return "low";
        }
        
        return "normal";
    }
    
    private String determineHeartRateStatus(HealthRecord record) {
        BigDecimal value = record.getValue();
        if (value == null) return "normal";
        
        int heartRate = value.intValue();
        
        // 心动过速判断标准 (> 100次/分)
        if (heartRate > 100) {
            return "high";
        }
        // 心动过缓判断标准 (< 60次/分)
        if (heartRate < 60) {
            return "low";
        }
        
        return "normal";
    }

    /**
     * 更新健康记录
     */
    public HealthRecord updateHealthRecord(Long id, HealthRecord healthRecord) {
        Optional<HealthRecord> existing = healthRecordRepository.findById(id);
        if (existing.isEmpty()) {
            throw new RuntimeException("健康记录不存在");
        }
        
        healthRecord.setId(id);
        return healthRecordRepository.save(healthRecord);
    }

    /**
     * 更新健康记录（重载方法）
     */
    public HealthRecord updateHealthRecord(HealthRecord healthRecord) {
        if (healthRecord.getId() == null) {
            throw new RuntimeException("健康记录ID不能为空");
        }
        return updateHealthRecord(healthRecord.getId(), healthRecord);
    }

    /**
     * 删除健康记录
     */
    public void deleteHealthRecord(Long id) {
        if (!healthRecordRepository.existsById(id)) {
            throw new RuntimeException("健康记录不存在");
        }
        healthRecordRepository.deleteById(id);
    }

    /**
     * 根据ID查找健康记录
     */
    public HealthRecord findById(Long id) {
        return healthRecordRepository.findById(id).orElse(null);
    }

    /**
     * 根据老人ID分页查询健康记录
     */
    public Page<HealthRecord> findByElderlyId(Long elderlyId, int page, int size) {
        Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "recordTime"));
        return healthRecordRepository.findByElderlyId(elderlyId, pageable);
    }

    /**
     * 分页查询所有健康记录
     */
    public Page<HealthRecord> findAll(int current, int size) {
        Pageable pageable = PageRequest.of(current - 1, size, Sort.by(Sort.Direction.DESC, "recordTime"));
        return healthRecordRepository.findAll(pageable);
    }

    /**
     * 根据记录类型分页查询
     */
    public Page<HealthRecord> findByRecordType(String recordType, int current, int size) {
        Pageable pageable = PageRequest.of(current - 1, size, Sort.by(Sort.Direction.DESC, "recordTime"));
        return healthRecordRepository.findByRecordType(recordType, pageable);
    }

    /**
     * 根据老人ID和记录类型查询
     */
    public Page<HealthRecord> findByElderlyIdAndRecordType(Long elderlyId, String recordType, int current, int size) {
        Pageable pageable = PageRequest.of(current - 1, size, Sort.by(Sort.Direction.DESC, "recordTime"));
        return healthRecordRepository.findByElderlyIdAndRecordType(elderlyId, recordType, pageable);
    }

    /**
     * 根据时间范围查询记录
     */
    public List<HealthRecord> findByElderlyIdAndTimeRange(Long elderlyId, LocalDateTime startTime, LocalDateTime endTime) {
        return healthRecordRepository.findByElderlyIdAndTimeRange(elderlyId, startTime, endTime);
    }

    /**
     * 获取最新的健康记录
     */
    public List<HealthRecord> getLatestRecords(Long elderlyId, int limit) {
        Pageable pageable = PageRequest.of(0, limit);
        return healthRecordRepository.findLatestByElderlyId(elderlyId, pageable).getContent();
    }

    /**
     * 根据状态查询记录
     */
    public Page<HealthRecord> findByStatus(String status, int current, int size) {
        Pageable pageable = PageRequest.of(current - 1, size, Sort.by(Sort.Direction.DESC, "recordTime"));
        return healthRecordRepository.findByStatus(status, pageable);
    }

    /**
     * 复合条件查询
     */
    public Page<HealthRecord> findByConditions(Long elderlyId, String recordType, String status, 
                                               LocalDateTime startTime, LocalDateTime endTime, 
                                               int current, int size) {
        Pageable pageable = PageRequest.of(current - 1, size, Sort.by(Sort.Direction.DESC, "recordTime"));
        return healthRecordRepository.findByConditions(elderlyId, recordType, status, startTime, endTime, pageable);
    }

    /**
     * 获取异常健康记录
     */
    public Page<HealthRecord> getAbnormalRecords(int current, int size) {
        return findByStatus("ABNORMAL", current, size);
    }

    /**
     * 获取健康记录总数
     */
    public long getTotalCount() {
        return healthRecordRepository.count();
    }

    /**
     * 检查健康记录是否异常
     */
    public boolean isAbnormal(HealthRecord record) {
        String recordType = record.getRecordType();
        BigDecimal value = record.getValue();
        
        if (value == null) {
            return false;
        }
        
        try {
            switch (recordType) {
                case "血压":
                    return checkBloodPressureAbnormal(record);
                case "血糖":
                    return checkBloodSugarAbnormal(value);
                case "体温":
                    return checkTemperatureAbnormal(value);
                case "心率":
                    return checkHeartRateAbnormal(value);
                default:
                    return false;
            }
        } catch (Exception e) {
            return false;
        }
    }

    private boolean checkBloodPressureAbnormal(HealthRecord record) {
        Integer systolic = record.getSystolicPressure();
        Integer diastolic = record.getDiastolicPressure();
        
        if (systolic == null || diastolic == null) {
            return false;
        }
        
        return systolic > 140 || systolic < 90 || diastolic > 90 || diastolic < 60;
    }

    private boolean checkBloodSugarAbnormal(BigDecimal value) {
        double bloodSugar = value.doubleValue();
        return bloodSugar > 11.1 || bloodSugar < 3.9;
    }

    private boolean checkTemperatureAbnormal(BigDecimal value) {
        double temperature = value.doubleValue();
        return temperature > 37.5 || temperature < 36.0;
    }

    private boolean checkHeartRateAbnormal(BigDecimal value) {
        int heartRate = value.intValue();
        return heartRate > 100 || heartRate < 60;
    }

    /**
     * 多条件搜索健康记录
     */
    public Page<HealthRecord> findWithFilters(int page, int size, Long elderlyId, String recordType, 
                                              LocalDateTime startTime, LocalDateTime endTime) {
        Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "recordTime"));
        return healthRecordRepository.findByConditions(elderlyId, recordType, null, startTime, endTime, pageable);
    }

    /**
     * 获取健康记录统计信息
     */
    public java.util.Map<String, Object> getStatistics() {
        java.util.Map<String, Object> stats = new java.util.HashMap<>();
        
        // 总记录数
        long totalCount = healthRecordRepository.count();
        stats.put("totalCount", totalCount);
        
        // 按类型统计
        java.util.Map<String, Long> typeStats = new java.util.HashMap<>();
        typeStats.put("blood_pressure", healthRecordRepository.countByRecordType("blood_pressure"));
        typeStats.put("temperature", healthRecordRepository.countByRecordType("temperature"));
        typeStats.put("heart_rate", healthRecordRepository.countByRecordType("heart_rate"));
        typeStats.put("blood_sugar", healthRecordRepository.countByRecordType("blood_sugar"));
        typeStats.put("weight", healthRecordRepository.countByRecordType("weight"));
        stats.put("typeStatistics", typeStats);
        
        // 按状态统计
        java.util.Map<String, Long> statusStats = new java.util.HashMap<>();
        statusStats.put("normal", healthRecordRepository.countByStatus("normal"));
        statusStats.put("high", healthRecordRepository.countByStatus("high"));
        statusStats.put("low", healthRecordRepository.countByStatus("low"));
        statusStats.put("abnormal", healthRecordRepository.countByStatus("abnormal"));
        stats.put("statusStatistics", statusStats);
        
        return stats;
    }
} 